import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:schoollifedemo/business/login/viewmodel/login_page_viewmodel.dart';

import 'package:schoollifedemo/commonwidget/button_widget.dart';
import 'package:schoollifedemo/commonwidget/common_dialog.dart';
import 'package:schoollifedemo/commonwidget/loading_widget.dart';
import 'package:schoollifedemo/commonwidget/text_widget.dart';
import 'package:schoollifedemo/commonwidget/common_base_page.dart';
import 'package:schoollifedemo/commonwidget/text_widget_with_overflow.dart';
import 'package:schoollifedemo/commonwidget/textfield_widget.dart';
import 'package:schoollifedemo/entity/Entity.dart';
import 'package:schoollifedemo/localization/local_text.dart';

class LoginPage extends BaseStatefulPage {
  const LoginPage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _LoginPageState();
  }
}

class _LoginPageState extends BasePageState<LoginPage> {
  final LoginPageViewModel _viewModel = LoginPageViewModel();
  String _initAccount = '';
  String _initPassword = '';

  String _account = '';
  String _password = '';

  bool _buttonEnable = false;

  Color _accountDefaultColor = const Color(0xFFB8DCFF);
  Color _passwordDefaultColor = const Color(0xFFB8DCFF);

  final Color _errorColor = const Color(0xFFE85252);
  final Color _focusBlueColor = const Color(0xFF529FE8);
  final Color _defaultBlueColor = const Color(0xFFB8DCFF);

  bool isAutoLoginCheck = false;

  int count = 0;
  DateTime? tapDownTime;
  DateTime? tapUpTime;

  @override
  void initState() {
    _viewModel.init();
    _viewModel
        .getIsAutoLoginFromSharedPreference(false)
        .asStream()
        .listen((isAutoLogin) async {
      if (isAutoLogin == true) {
        String? saveAccount = await _viewModel.getAccountFromSharedPreference();
        String? savePassword =
            await _viewModel.getPasswordFromSharedPreference();
        if (saveAccount == null) {
          return;
        }
        if (savePassword == null) {
          return;
        }
        // 自动登录效果
        bool? isLogin = await _viewModel.loginAccountWithPassword(
          account: saveAccount,
          password: savePassword,
          isAutoLogin: true,
        );
        if (isLogin == true) {
          _viewModel.setLoginAccount(saveAccount); // 记录登录账号
          _viewModel.gotoHomePage(context);
        } else {
          _initAccount = saveAccount;
          _initPassword = savePassword;
          setState(() {});
        }
      }
    });

    super.initState();
  }

  @override
  void dispose() {
    _viewModel.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false, // 适配键盘高度问题，界面不重写
      body: GestureDetector(
        onTap: () {
          // 取消焦点
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: Container(
          width: MediaQuery.of(context).size.width,
          color: Colors.white,
          padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
          child: ListView(
            physics: const BouncingScrollPhysics(),
            children: [
              Column(
                children: [
                  GestureDetector(
                    onTapDown: (detail) {
                      tapDownTime = DateTime.now();
                    },
                    onTapUp: (detail) {
                      if(count == 5){
                        // _viewModel
                      }
                      tapUpTime = DateTime.now();

                    },
                    child: Container(
                      margin: const EdgeInsets.only(top: 70),
                      child: const TextWidgetWithOverflow(
                        LoginLocalText.welcomeTitle,
                        width: 250,
                        height: 60,
                        paddingLeft: 50,
                        paddingRight: 50,
                        paddingTop: 10,
                        paddingBottom: 10,
                        radius: 30,
                      ),
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.only(top: 50),
                    child: Stack(
                      children: [
                        const TextWidget(
                          LoginLocalText.account,
                          height: 60,
                          textAxis: MainAxisAlignment.start,
                          fontSize: 16,
                          paddingLeft: 22,
                        ),
                        Container(
                          margin: const EdgeInsets.only(left: 80),
                          child: TextFieldWidget(
                            width: 200,
                            height: 60,
                            initText: _initAccount,
                            textAlign: TextAlign.center,
                            maxLength: 20,
                            insideColor: _accountDefaultColor,
                            enableCountText: false,
                            onTextChange: (text) {
                              _account = text;
                              _checkButtonEnable();
                              setState(() {});
                            },
                            onFocus: (isFocus) {
                              if (isFocus) {
                                _accountDefaultColor = _focusBlueColor;
                              } else {
                                _accountDefaultColor = _defaultBlueColor;
                              }
                              setState(() {});
                            },
                            formatterList: [
                              FilteringTextInputFormatter(
                                RegExp("[a-zA-Z]"),
                                allow: true,
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.only(top: 30),
                    child: Stack(
                      children: [
                        const TextWidget(
                          LoginLocalText.password,
                          height: 60,
                          textAxis: MainAxisAlignment.start,
                          fontSize: 16,
                          paddingLeft: 22,
                        ),
                        Container(
                          margin: const EdgeInsets.only(left: 80),
                          child: TextFieldWidget(
                            initText: _initPassword,
                            width: 200,
                            height: 60,
                            textAlign: TextAlign.center,
                            isPassword: true,
                            maxLength: 20,
                            enableCountText: false,
                            insideColor: _passwordDefaultColor,
                            onTextChange: (text) {
                              _password = text;
                              _checkButtonEnable();
                              setState(() {});
                            },
                            onFocus: (isFocus) {
                              if (isFocus) {
                                _passwordDefaultColor = _focusBlueColor;
                              } else {
                                _passwordDefaultColor = _defaultBlueColor;
                              }
                              setState(() {});
                            },
                            formatterList: [
                              FilteringTextInputFormatter(
                                RegExp("[a-zA-Z0-9]"),
                                allow: true,
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.only(top: 20),
                    height: 30,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Checkbox(
                          value: isAutoLoginCheck,
                          onChanged: (changeValue) {
                            isAutoLoginCheck = !isAutoLoginCheck;
                            _checkButtonEnable();
                            setState(() {});
                          },
                          shape: const CircleBorder(),
                        ),
                        GestureDetector(
                          onTap: () {
                            isAutoLoginCheck = !isAutoLoginCheck;
                            setState(() {});
                          },
                          child: const TextWidgetWithOverflow(
                            LoginLocalText.isAutoLogin,
                            fontSize: 12,
                            width: 100,
                          ),
                        ),
                      ],
                    ),
                  ),
                  StreamBuilder(
                    initialData: CommonLoadingState.successTypeOne,
                    stream: _viewModel.loginStateSubject,
                    builder: (builder, spot) {
                      CommonLoadingState? loadingState =
                          spot.data as CommonLoadingState?;
                      switch (loadingState) {
                        case CommonLoadingState.loading:
                          return Container(
                            margin: const EdgeInsets.only(top: 30),
                            width: 80,
                            height: 50,
                            child: const LoadingWidget(),
                          );
                        case CommonLoadingState.successTypeOne:
                          return _rightArrowButton(context);
                        case CommonLoadingState.successTypeTwo:
                          return _rightArrowButton(context);
                        default:
                          return _rightArrowButton(context);
                      }
                    },
                  ),
                  Container(
                    margin: const EdgeInsets.only(top: 120),
                    child: ButtonWidget(
                      width: 100,
                      height: 50,
                      radius: 50,
                      insideWidget: const Text(LoginLocalText.registerTitle),
                      onButtonClick: () {
                        _viewModel.turnToRegisterPage(context);
                      },
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _rightArrowButton(BuildContext context) {
    return Container(
      margin: const EdgeInsets.only(top: 30),
      child: ButtonWidget(
        insideWidget: Image.asset('assets/images/common/img_arrow_right.png'),
        width: 80,
        height: 50,
        radius: 50,
        onButtonClick: !_buttonEnable
            ? null
            : () async {
                bool? isLogin = await _viewModel.loginAccountWithPassword(
                    account: _account, password: _password);
                if (isLogin == true) {
                  // 成功登录之后，会记录内容，如果不是成功登录，那么不记录
                  if (isAutoLoginCheck) {
                    _viewModel.saveAccountAndPasswordToSharedPreference(
                        _account, _password);
                  }
                  // 记录是否记录用户选择自动连接的内容
                  _viewModel
                      .saveIsAutoLoginToSharedPreference(isAutoLoginCheck);
                  // 设置当前设备的account
                  _viewModel.setLoginAccount(_account);
                  _viewModel.gotoHomePage(context);
                } else if (isLogin == false) {
                  _accountDefaultColor = _errorColor;
                  _passwordDefaultColor = _errorColor;
                  DialogUtils.showSimpleDialog(
                    context,
                    title: LoginLocalText.error,
                    clickOutSideDismiss: true,
                    widgets: Center(
                      child: TextWidgetWithOverflow(
                        LoginLocalText.accountOrPasswordError,
                        insideColor: _errorColor,
                        fontSize: 16,
                        textColor: Colors.white,
                        textAlign: TextAlign.center,
                        maxLine: 2,
                      ),
                    ),
                  );
                } else {
                  DialogUtils.showSimpleDialog(
                    context,
                    title: LoginLocalText.error,
                    clickOutSideDismiss: true,
                    widgets: Center(
                      child: TextWidgetWithOverflow(
                        LoginLocalText.networkErrorOrServerError,
                        fontSize: 16,
                        maxLine: 2,
                        height: 50,
                        textAlign: TextAlign.center,
                        textColor: Colors.white,
                        insideColor: _errorColor,
                      ),
                    ),
                  );
                }
              },
      ),
    );
  }

  void _checkButtonEnable() {
    if (_account.isNotEmpty != true) {
      _buttonEnable = false;
      return;
    }
    if (_password.isNotEmpty != true) {
      _buttonEnable = false;
      return;
    }
    _buttonEnable = true;
    return;
  }
}
